<?php

require_once SITE_ROOT_PATH.'/_lib/classes/class.tree.php';
require_once SITE_ROOT_PATH.'/_lib/classes/class.hotels.php';
require_once SITE_ROOT_PATH.'/_lib/classes/class.hotels.php';
require_once SITE_ROOT_PATH."/_lib/classes/class.suppliers.php";
require_once SITE_ROOT_PATH."/_lib/classes/class.hotel_supplier_low.php";



class hotelSearch {
 
    
    function getParams(){
        
        
        $suppliers = new suppliers();


        if(count($_POST)){

            $search_params = $this->setCriteria($_POST); 

            $results = $suppliers->hotel_search($search_params);
            $results = $this->inc_search_params($results, $search_params);
            $results = $this->multiply_prices($results);
            $results = $this->default_sort($results);
// Store results in session for caching
            $_SESSION["hotels_search_results"] = array("data"=>$results, "timestamp"=>time());                        
// Store search form data to cookie
           $this->store_search_params($search_params['search_params']);
            // redirect browser to search results page
            // avoid search repeat when refreshing browser
            header("Location: hotel_results.php?page=1");
            exit;


          }else{

            // check for search results and booking timeouts (see: common.php)
            //if($location = check_timeouts()) {
                // header("Location: $location");
                //exit;
            //}

            // set results variable in the class
            $suppliers->set_results($_SESSION["hotels_search_results"]["data"]);

            // pagenator action - not yet active 
            $results = $suppliers->hotel_list($page);
            
            
            
            // fetch additional data (resorts, photos) for displayed results
            // returns $results
            $results = $this->fetch_additional_hotel_data($results);
            $_SESSION['hotels_search_results']['data'] = $results;           
           
           }
           
           return $results;

        
    }

   function setCriteria($params) {  
    $day = $params["date_day"];
    $month = substr($params["date_month"],0,2);
    $year = substr($params["date_month"],5,2);
    $params["arrival_date"] = mktime(0, 0, 0, $month, $day, $year); 

    // convert destination_tree_id to destination_id for supplier
    $tree = new tree();
    $aparams = array('tree_id' => $params["destination_tree_master_id"]);
    $destination_values = $tree->get_branch($aparams, '1');
    $destination_values = $destination_values[0]; 
    $low = new hotel_supplier_low();    
    $locations_low = $low->get_resorts_from_table($params["destination_tree_id"]);
    $resorts_low_list = $this->resort_results_2_list($locations_low,'resort_id');                          
    if ($destination_values['youtravel_id']) {
        $params['youtravel_id'] = $destination_values['youtravel_id'];
    }    
 
    if ($locations_low[0]['region_id']) {
        $params['lowcostbeds_regionID'] = $locations_low[0]['region_id'];
    }
    
    if ($resorts_low_list) {
        $params['lowcostbeds_resortID'] = $resorts_low_list;
    }    
    
    
    return array('search_params'=>$params, 'destination_values' => $destination_values);
    
}

function resort_results_2_list($result,$mykey){
    
    $resorts = array();
    foreach($result as $value){                
        $resorts[] = $value[$mykey];
    }
    return $resorts;
    
    
}


    function multiply_prices($results) {
        $coef = COMISSION_PERCENT;
        foreach ($results["hotels"] as $id=>$hotel) {
            foreach ($hotel["room_sets"] as $room_set_id=>$room_set) {
                if ($room_set["rooms"]) {
                    foreach ($room_set["rooms"] as $i=>$room) {
                        $rateOrig   = $results["hotels"][$id]["room_sets"][$room_set_id]["rooms"][$i]["Rate"];
                        $rateMarkup = ceil($rateOrig/$coef);

                        // save original price and price with markup
                        $results["hotels"][$id]["room_sets"][$room_set_id]["rooms"][$i]["RateOrig"] = $rateOrig;
                        $results["hotels"][$id]["room_sets"][$room_set_id]["rooms"][$i]["Rate"]     = $rateMarkup;

                        // Board basis desc
                        $bb_code = $results["hotels"][$id]["room_sets"][$room_set_id]["rooms"][$i]["Board"];
                        $results["hotels"][$id]["room_sets"][$room_set_id]["rooms"][$i]["board_desc"] = $this->get_board_basis_description($bb_code);
                    }
                }
            }
        }
        return $results;
    }

    
    
    function postprocess_results($params) {
        $res = array();
        foreach ($params['hotels'] as $hotel) {
            switch ($hotel['supplier_code']) {
                case 'you':
                    $res[$hotel['hotel_id_youtravel']] = $hotel;
                break;
                case 'low':
                    $res[$hotel['hotel_id_lowcostbeds']] = $hotel;
                break;
                default:
                    $res[] = $hotel;
                break;
            }
        }
        $params['hotels'] = $res;
        return $params;
    }
    
    
    
    
    
    /* sorts hotels by price from lowest, and rooms by price from lowest */
    function default_sort($results) {
        // sort rooms for each hotel
        foreach ($results["hotels"] as $id=>$hotel) {
            $cheapest_room_price = 0;
            foreach ($hotel["room_sets"] as $room_set_id=>$room_set) {
                if ($room_set["rooms"]) {
                    uasort($room_set["rooms"], array($this,"compare_rooms"));
                    $results["hotels"][$id]["room_sets"][$room_set_id] = $room_set;
                    $room = array_shift($room_set["rooms"]);
                    $price = $room["Rate"];
                    if($cheapest_room_price > $price || $cheapest_room_price == 0) {
                        $cheapest_room_price = $price;
                    }
                }
            }
            // remember the cheapest room for each hotel
            $results["hotels"][$id]["cheapest_room"] = $cheapest_room_price;
        }
        // sort hotels by cheapest room
        uasort($results["hotels"], array($this,"compare_hotels"));    
        return $results;
    }
    
    

   
    
    
    
    
// append the hotel and destination data to the search results
function fetch_additional_hotel_data($results) {
//    $hotels = new hotels();
//    $tree = new tree();
    if (!is_array($results["hotels"])) {
        return false;
    }

//    $i=0;
    foreach ($results["hotels"] as $id => $hotel ) {
        //print_r($hotel); die();       
        // get the hotel values       
        /*$params['tree_id'] = $hotel_id;
        $lookup = $hotels->lookup_hotel($params);
        unset($params);*/
        //print_r($hotel); die();
        $hotel_id = $hotel['hotel_id_lowcostbeds'];
        

        unset($params);

        // Set values
       // if (FEATURE_HOTEL_MAPPING) {
            /*
            $hotel_values = $lookup['hotel_values'];
            $resort_values = $lookup['resort_values'];
            $destination_values = $lookup['destination_values'];
            $results["hotels"][$hotel_id]["resort"] = $resort_values;
            $results["hotels"][$hotel_id]["destination"] = $destination_values;
            $results["hotels"][$hotel_id]["board_basis"] = $this->get_board_basis_description($bb_code);
            $lead_hotel_thumb_url = $tree->photo_url($hotel_values['main_photo']);    
            $results["hotels"][$hotel_id]["thumb"] = $lead_hotel_thumb_url;*/
        //} else {
            
            
            //if($supplier = 'low'){
            $hotel_supplier_low = new hotel_supplier_low();
            $low_hotel_desc = $hotel_supplier_low->get_hotel_description($hotel_id);
            $hotel['thumb'] = $low_hotel_desc[0]['ThumbnailURL'];
            $hotel['rating'] = $low_hotel_desc[0]['Rating'];
            $hotel['photos'][] = $low_hotel_desc[0]['Image1URL'];
            $hotel['photos'][] = $low_hotel_desc[0]['Image2URL'];
            $hotel['photos'][] = $low_hotel_desc[0]['Image3URL'];
            $hotel['hotel_name'] = $low_hotel_desc[0]['Property'];
            $hotel['hotel_description'] = $low_hotel_desc[0]['Description'];
            $hotel['hotel_resort'] = $low_hotel_desc[0]['resort'];
            $hotel['hotel_destination'] = $low_hotel_desc[0]['region'];
            $hotel['tree_id'] = $low_hotel_desc[0]['tree_id'];
            $hotel['hotel_id'] = $hotel_id;
        $hotel_array[$id] = $hotel;
    }
    
    $results['hotels'] = $hotel_array;
    
    return $results;
}



function get_board_basis_description($bb_code) {
    switch($bb_code){
        case "RO";
            return "Room only";
        break;
        case "SC";
            return "Self catering";
        break;
        case "BB";
            return "Bed & breakfast";
        break;
        case "HB";
            return "Half board";
        break;
        case "AI";
            return "All inclusive";
        break;
        case "FB";
            return "Full Board";
        break;
        default;
            return "$bb_code";
        break;
    }
}
    





function compare_rooms($a, $b) {
    if ($a["Rate"]==$b["Rate"]) {
        return 0;
    }
    return ($a["Rate"] < $b["Rate"]) ? -1 : 1;
}

function compare_hotels($a, $b) {
    if ($a["cheapest_room"] == $b["cheapest_room"]) {
        return 0;
    }
    return ($a["cheapest_room"] < $b["cheapest_room"]) ? -1 : 1;
}






function store_search_params($params){
    // store search params in cookies  
    setcookie("destination_tree_id", $params['destination_tree_id'], 0, "/");
    setcookie("destination_tree_master_id", $params['destination_tree_master_id'], 0, "/");
    setcookie("date_day", $params['date_day'], 0, "/");
    setcookie("date_month", $params['date_month'], 0, "/");
    setcookie("nights", $params['nights'], 0, "/");
    setcookie("no_rooms", $params['no_rooms'], 0, "/");
    setcookie("room_adults_1", $params['room_adults_1'], 0, "/");
    setcookie("room_children_1", $params['room_children_1'], 0, "/");

    if ($params['no_rooms']>1) {
        setcookie("room_adults_2", $params['room_adults_2'], 0, "/");
        setcookie("room_children_2", $params['room_children_2'], 0, "/");      
    }
    if ($params['no_rooms']>2) {
        setcookie("room_adults_3", $params['room_adults_3'], 0, "/");
        setcookie("room_children_3", $params['room_children_3'], 0, "/");      
    }
    /*if ($GLOBALS["note"]) {
        $_SESSION["note"] = $GLOBALS["note"];
    }*/
}

function fetch_destination_data($params){
    

    $tree = new tree();

    $aparams['tree_id'] = $params['destination_tree_id'];
    $destination_values = $tree->get_branch($aparams);
    unset($aparams);
    $destination_values = $destination_values[0];

    return $destination_values;
    
    
}


function inc_search_params($results, $params){
    
    $results['destination_values'] = $params['destination_values'];
    $results['search_params'] = $params['search_params'];
    
    return $results;      

    
    } 

    

}
